#include "tcpserverbase.h"

PUBLIC_FUNCTION_BEGIN

TcpServerBase::TcpServerBase()
    :m_pMessageSend(nullptr)
{
}

TcpServerBase::~TcpServerBase()
{
    DELETE_POINTER(m_pMessageSend);
}

TCPSERVER_METHOD_SETGET(Port, quint16, m_nPort)
TCPSERVER_METHOD_SETGET(HostAdd, QHostAddress, m_haHostAdd)

bool TcpServerBase::StartListen(QHostAddress haHostAdd, quint16 nPort)
{
    BeforeStartListen();

    bool nRet = false;
    m_haHostAdd = haHostAdd;
    m_nPort = nPort;

    m_pMessageSend = new TcpSendThread(&m_mutexSendLock, this);

    if ( !isListening() )
        nRet = listen(m_haHostAdd, m_nPort);
    if ( nRet )
    {
        SuccessStartListen();
    }

    AfterStartListen();

    return nRet;
}

void TcpServerBase::sendMessage(QByteArray qbaSendMessage, int nSocketDescriptor)
{
    SendStruct ss;
    ss.nSocketDescriptor = nSocketDescriptor;
    ss.qbaSendMessage = qbaSendMessage;

    m_mutexSendLock.lock();

    m_listSendStruct.append(ss);

    m_mutexSendLock.unlock();

    //if( false == m_pMessageSend->isRunning() )
        //m_pMessageSend->start();

//    int nRet = true;
//    if ( SOCKET_DESCRIPTOR_ALL != nSocketDescriptor )
//    {
//        int ii;
//        for(ii = 0; ii < m_listTcpSocket.count(); ++ii)
//        {
//            if ( nSocketDescriptor == m_listTcpSocket.at(ii)->socketDescriptor())
//                break;
//        }
//        if ( ii > m_listTcpSocket.count() )
//            nRet = false;
//        QTcpSocket* pqtcpsocket = m_listTcpSocket.at(ii);
//        ASSERT(pqtcpsocket);
//        if ( pqtcpsocket->write(qbaSendMessage) )
//            nRet = false;
//    }
//    else
//    {
//        foreach ( QTcpSocket* pqtcpsocket, m_listTcpSocket) {
//            if ( pqtcpsocket->write(qbaSendMessage) )
//                nRet = false;
//        }
//    }
//    return nRet;
}

PUBLIC_FUNCTION_END

PROTECTED_FUNCTION_BEGIN

void TcpServerBase::SuccessStartListen()
{
    DeleteInvalidSocket();
    connect(this, SIGNAL(newConnection()), this, SLOT(slotNewComing()));
}

PROTECTED_FUNCTION_END

PRIVATE_FUNCTION_BEGIN

void TcpServerBase::DeleteInvalidSocket()
{
    foreach (QTcpSocket* pqtcpsocket, m_listTcpSocket) {
        if( !pqtcpsocket->isValid() )
            m_listTcpSocket.removeOne(pqtcpsocket);
    }
}

PRIVATE_FUNCTION_END

PROTECTED_SLOT_FUNCTION_BEGIN

void TcpServerBase::slotNewComing()
{
    QTcpSocket* pqtcpsocket = nextPendingConnection();
    if (pqtcpsocket->isValid())
    {
        m_listTcpSocket.append(pqtcpsocket);
        connect(pqtcpsocket, SIGNAL(readyRead()), this, SLOT(getMessage()));
    }
}

void TcpServerBase::getMessage()
{
    QTcpSocket* pqtcpsocket = (QTcpSocket*)sender();
    ASSERT(pqtcpsocket);
    QByteArray qba;
    qba.append( pqtcpsocket->socketDescriptor() );
    qba.append( pqtcpsocket->readAll() );
    m_listqaRecMessage.append(qba);
//#ifdef  _DEBUG
    //QDebug()<<QString(qba);
//#endif  //_DEBUG
    //DeMessage();
    ReadyMessage();
}

PROTECTED_SLOT_FUNCTION_END
